PageController = Class.create({
  initialize : function() {
    
    this._pageButtonClickListener = this._onPageButtonClick.bindAsEventListener(this);
    
    this._addButton("Vaihda etusivulle", 'INDEX');

    var _this = this;
    new Ajax.Request(CONTEXTPATH + "/_app?action=QUERY_META", {
      onSuccess: function (transport) {
        var jsonResponse = transport.responseText.evalJSON();
        for (var i = 0, l = jsonResponse.pages.length; i < l; i++) {
          if (jsonResponse.pages[i].type == 'THESIS_SCALE_2D') {
            _this._addButton("Vaihda sivulle: " + jsonResponse.pages[i].number + ' - ' + jsonResponse.pages[i].title, jsonResponse.pages[i].number);
          } else {
            _this._addButtonDisabled("(Ei 2d skaala " + jsonResponse.pages[i].number + ' - ' + jsonResponse.pages[i].title); 
          }
        }
      }
    });
  },
  _addButton: function (text, value) {
    var button = new Element("div", {
      className: "controlPageButton"
    }).update(text);
    button._page = value;
    
    Event.observe(button, "click", this._pageButtonClickListener);
    
    document.body.appendChild(button);
  },
  _addButtonDisabled: function (text) {
    var button = new Element("div", {
      className: "controlPageButton controlPageButtonDisabled"
    }).update(text);
    document.body.appendChild(button);
  },
  _notify: function (message) {
    $('notification').update(message);
    
    new S2.FX.Morph($('notification'), {
      style: 'color: #000',
      duration: 0.5
    }).play();
  },
  _onPageButtonClick: function (event) {
    var button = Event.element(event);
    var page = button._page;
    
    var _this = this;
    new Ajax.Request(CONTEXTPATH + "/_app?action=CONTROL&ctrlaction=PAGE&args=" + page, {
      onSuccess: function () {
        _this._notify('Pyyntö lähetetty');
        setTimeout(function () {
          $('notification').update('&nbsp;');
          new S2.FX.Morph($('notification'), {
            style: 'color: #aaa',
            duration: 0.5
          }).play();
        }, 3000);
      }
    });
  }
});

document.observe("dom:loaded", function(event) {
  window._pageController = new PageController();
});